package com.chuanyang.driverh.mainorder;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.adapter.LookGoodAdapter;
import com.chuanyang.driverh.mainother.LookPhotoDetailActivity;
import com.chuanyang.driverh.responseresult.LookWaybillData;
import com.chuanyang.driverh.responseresult.LookWaybillDetailData;
import com.chuanyang.driverh.responseresult.LookWaybillDetailResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.WindowUtils;
import com.chuanyang.driverh.utils.eventbus.RefleshDelieryEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.CustomMeasureHeightListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class LookWaybillDetailActivity extends BaseTitleActivity {
    private LookWaybillData.DataBean waybillData;
    private LookGoodAdapter adapter;
    private ImageView iv_waybill_details_img;
    private ImageView iv_waybill_car_img1;
    private ImageView iv_waybill_car_img2;
    private ImageView iv_waybill_car_img3;
    private ImageView iv_waybill_phone;
    private RatingBar rb_waybillinfo_stars;
    private TextView tv_waybill_details_status;
    private TextView tv_waybill_details_name;
    private TextView tv_waybill_role;
    private TextView tv_waybill_phone;
    private TextView tv_waybill_fleet;
    private TextView tv_waybill_car_id;
    private TextView tv_order_no;
    private TextView tv_time;
    private TextView tv_waybill_code;
    private LinearLayout ll_waybill_div;
    private TextView tv_waybill_car_id1;
    private int status;
    private int position;
    private TextView tv_waybill_time;
    private TextView tv_waybill_act;

    ArrayList<LookWaybillDetailData.DataBean> list;
    private CustomMeasureHeightListView ll_waybill_orderlist;
    private Dialog dialog;

    @Override
    protected int getContentResId() {
        return R.layout.order_act_lookwaybilldetail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        //司机图像
        iv_waybill_details_img = (ImageView) findViewById(R.id.iv_waybill_details_img);
        ll_waybill_div = (LinearLayout) findViewById(R.id.ll_waybill_div);
        iv_waybill_car_img1 = (ImageView) findViewById(R.id.iv_waybill_car_img1);
        iv_waybill_car_img2 = (ImageView) findViewById(R.id.iv_waybill_car_img2);
        iv_waybill_car_img3 = (ImageView) findViewById(R.id.iv_waybill_car_img3);
        //司机电话
        iv_waybill_phone = (ImageView) findViewById(R.id.iv_waybill_phone);
        //司机评分
        rb_waybillinfo_stars = (RatingBar) findViewById(R.id.rb_waybillinfo_stars);
        //运输状态
        tv_waybill_details_status = (TextView) findViewById(R.id.tv_waybill_details_status);
        //司机姓名
        tv_waybill_details_name = (TextView) findViewById(R.id.tv_waybill_details_name);
        //身份 队员还是队长
        tv_waybill_role = (TextView) findViewById(R.id.tv_waybill_role);
        //电话
        tv_waybill_phone = (TextView) findViewById(R.id.tv_waybill_phone);
        //车队名称
        tv_waybill_fleet = (TextView) findViewById(R.id.tv_waybill_fleet);
        //车牌或者船的救助号
        tv_waybill_car_id = (TextView) findViewById(R.id.tv_waybill_car_id);
        //订单号
        tv_order_no = (TextView) findViewById(R.id.tv_order_no);
        //时间
        tv_time = (TextView) findViewById(R.id.tv_time);
        //出库单号
        tv_waybill_act = (TextView) findViewById(R.id.tv_waybill_act);
        //运单号
        tv_waybill_code = (TextView) findViewById(R.id.tv_waybill_code);
        tv_waybill_time = (TextView) findViewById(R.id.tv_waybill_time);

        ll_waybill_orderlist= (CustomMeasureHeightListView) findViewById(R.id.ll_waybill_orderlist);


    }

    @Override
    protected void initData() {
        setBackImg();
        getTitleTextView().setText("运单信息");
        list=new ArrayList();
        Intent intent=getIntent();
        waybillData = (LookWaybillData.DataBean) intent.getSerializableExtra("LookWaybill");
        position = intent.getIntExtra("position",-1);
        adapter = new LookGoodAdapter(this,list);
        ll_waybill_orderlist.setAdapter(adapter);
        fillView();
        getWayBillData();
    }

    @Override
    protected void initListener() {
        iv_waybill_phone.setOnClickListener(this);
        iv_waybill_car_img1.setOnClickListener(this);
        iv_waybill_car_img2.setOnClickListener(this);
        iv_waybill_car_img3.setOnClickListener(this);
        tv_waybill_act.setOnClickListener(this);

    }

    public void onEventMainThread(RefleshDelieryEvent event) {
        if (event.isReflesh()) {
            getWayBillData();
        }
    }
    private void fillView() {
        tv_waybill_time.setText(waybillData.getCreatetime());
        rb_waybillinfo_stars.setRating(waybillData.getStar());
        tv_waybill_details_name.setText(waybillData.getDriverName());
        tv_waybill_phone.setText(waybillData.getPhone());
        if(waybillData.getFleetType().equals("2")) {
            tv_waybill_fleet.setText("所属车队：" + waybillData.getFleetName());
            tv_waybill_car_id.setText("车牌号："+waybillData.getPlateNumber());

        }
        else {
            tv_waybill_fleet.setText("所属船队：" + waybillData.getFleetName());
            tv_waybill_car_id.setText("记助号："+waybillData.getPlateNumber());


        }
        // tv_waybill_fleet.setText("所属队伍：" + waybillData.getFleetName());
        tv_order_no.setText("订单号："+waybillData.getOrderNo());
        tv_waybill_code.setText(waybillData.getWaybillNo());
        tv_time.setText(waybillData.getCreatetime());
        ratioImage(iv_waybill_car_img1);
        ratioImage(iv_waybill_car_img2);
        ratioImage(iv_waybill_car_img3);
        BitmapUtil.showImgForNetPath( waybillData.getUserImage(),iv_waybill_details_img);
//        YncApplication.getInstance().loadCircleImage(this, waybillData.getUserImage(), R.drawable.shengfeng, R.drawable.shengfeng, iv_waybill_details_img);
        try {
            status = waybillData.getWaybillStatus();
        }
        catch (Exception e) {
            status = -1;
        }
        if (status < 0) {
            tv_waybill_details_status.setText("运单异常");
            getRightTextView().setText("删除");
        } else if (waybillData.getWaybillStatus()==0) {
            tv_waybill_details_status.setText("初始化");
            getRightTextView().setText("删除");

        } else if (waybillData.getWaybillStatus()==2) {
            tv_waybill_details_status.setText("待装货");
            getRightTextView().setText("删除");

        } else if (waybillData.getWaybillStatus()==3) {
            tv_waybill_details_status.setText("装货中");
            getRightTextView().setText("删除");

        } else if (waybillData.getWaybillStatus()==4) {
            tv_waybill_details_status.setText("运输中");
            getRightTextView().setText("删除");

        } else if (waybillData.getWaybillStatus()==5) {
            tv_waybill_details_status.setText("卸货中");
            getRightTextView().setText("删除");

        } else if (waybillData.getWaybillStatus()==6) {
            tv_waybill_details_status.setText("待确认收货");
            getRightTextView().setText("");

        } else if (waybillData.getWaybillStatus()==7) {
            tv_waybill_act.setVisibility(View.GONE);
            tv_waybill_details_status.setText("已完成");
            getRightTextView().setText("");


        }


        //填充车辆照片
        if(waybillData.getWaybillUnlaodImgs()!=null&&waybillData.getWaybillUnlaodImgs().size()>0)
        {
            List<LookWaybillData.WaybillUnloadImag> imgs=waybillData.getWaybillUnlaodImgs();
            if (!TextUtils.isEmpty(imgs.get(0).getImage())) {
                BitmapUtil.showImgForNetPath( imgs.get(0).getImage(),iv_waybill_car_img1);

            } else {
                iv_waybill_car_img1.setVisibility(View.GONE);
            }
            if (imgs.size()>=2&&!TextUtils.isEmpty(imgs.get(1).getImage())) {
                BitmapUtil.showImgForNetPath(imgs.get(1).getImage(),iv_waybill_car_img2);

            } else {
                iv_waybill_car_img2.setVisibility(View.GONE);

            }
            if (imgs.size()>=3&&!TextUtils.isEmpty(imgs.get(2).getImage())) {
                BitmapUtil.showImgForNetPath(imgs.get(2).getImage(),iv_waybill_car_img3);
            } else {
                iv_waybill_car_img3.setVisibility(View.GONE);

            }
        }
        else {
            ll_waybill_div.setVisibility(View.GONE);
        }

    }

    @Override
    protected void baseGoEnsure() {
        if(TextUtils.isEmpty(mBaseEnsure.getText())) {
            return;
        }
        dialog= DialogUtil.myDialog(activityContext, "删除运单", "取消", "确定", "确定删除运单？", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        deleteWaybill(waybillData.getWaybillId() + "");
                        break;
                }
                dialog.cancel();
            }
        });
    }

    private void getWayBillData() {
        DialogUtil.showLoadingDialog(activityContext,"订单...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("waybillId",waybillData.getWaybillId()+"");
        MyHttpUtil.selectByWaybillId(activityContext,params, new MyCallback<LookWaybillDetailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(LookWaybillDetailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if(result.getData().getData().size()>0)
                    {
                        adapter.setNewData(result.getData().getData());
                    }
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });



    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId())
        {
            case  R.id.iv_waybill_phone:
                if (waybillData.getPhone() != null) {
                    dialog= DialogUtil.myDialog(activityContext, "拨打电话", "取消", "确定", "确定拨打："+waybillData.getPhone(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()){
                                case R.id.dialog_btn_left:
                                    break;
                                case R.id.dialog_btn_right:
                                    DialogUtil.dial(activityContext,waybillData.getPhone());
                                   /* Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + waybillData.getPhone()));
                                    try {
                                        if (PermissoinUtil.checkAndRequestPermission(activityContext, android.Manifest.permission.CALL_PHONE, "请给应用添加拨打电话的权限！"))
                                            startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }*/
                                    break;
                            }
                            dialog.cancel();
                        }
                    });
                }
                break;
            case  R.id.iv_waybill_car_img1:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext,LookPhotoDetailActivity.class).putExtra("data",waybillData.getWaybillUnlaodImgs().get(0).getImage()));

                break;
            case  R.id.iv_waybill_car_img2:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext,LookPhotoDetailActivity.class).putExtra("data", waybillData.getWaybillUnlaodImgs().get(1).getImage()));

                break;
            case  R.id.iv_waybill_car_img3:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext,LookPhotoDetailActivity.class).putExtra("data", waybillData.getWaybillUnlaodImgs().get(2).getImage()));
                break;
            case  R.id.tv_waybill_act:
                Intent intent=new Intent(this,DeliveryOrderActivity.class);
                intent.putExtra("driverId",waybillData.getDriverId());
                intent.putExtra("data",waybillData.getWaybillId()+"");
                startActivity(intent);
                break;
//            case R.id.bt_waybill_act:
//
//                    MyDialog.whethierDeleteWaybill(LookWaybillDetailActivity.this, handler );
//
//
//                break;

        }
    }
    //根据运单id删除运单
    private void deleteWaybill(String waybillId) {
        DialogUtil.showLoadingDialog(activityContext,"订单...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("waybillId", waybillId);
        MyHttpUtil.deleteWaybill(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    Intent intent = new Intent();
                    intent.putExtra("position", position);
                    setResult(2,intent);
                    //2.结束这个窗口
                    finish();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });


    }

    /**
     * 设置图片的高度和宽度相等，且每张图占屏幕面积的1/3
     * @param img
     */
   private  void ratioImage(ImageView img)
    {

        int srceenWide= WindowUtils.getScreenWide(this);
        float pix= WindowUtils.getPixel(this);
        img.measure(0,0);
        int imgWide=(int)((srceenWide-40*pix)/3);
        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) img.getLayoutParams();
        params.width=imgWide;
        params.height=imgWide;
        img.requestLayout();
    }



}
